package com.wsgxj.service.sys.impl;

import com.wsgxj.domain.sys.SysMenu;
import com.wsgxj.domain.sys.SysUser;
import com.wsgxj.mapper.sys.SysMenuMapper;
import com.wsgxj.mapper.sys.SysRoleMenuMapper;
import com.wsgxj.mapper.sys.SysUserRoleMapper;
import com.wsgxj.service.sys.SysMenuService;
import com.wsgxj.vo.DataGridResult;
import com.wsgxj.vo.Query;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Service
public class SysMenuServiceImpl implements SysMenuService {
	
	@Autowired
	private SysMenuMapper sysMenuMapper;
	@Autowired
	private SysRoleMenuMapper sysRoleMenuMapper;
	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;

	@Override
	public DataGridResult getPageList(Query query) {
		Integer offset = (Integer) query.get("offset");
		Integer limit = (Integer) query.get("limit");
		String menuName = (String) query.get("menuName");
		
		List<SysMenu> rows = sysMenuMapper.find(offset, limit, menuName);
		Long total = sysMenuMapper.count(menuName);

        DataGridResult result = new DataGridResult(total, rows);
		return result;
	}

	@Override
	public void deleteBatch(Long[] ids) {
		sysMenuMapper.deleteBatch(ids);
		sysRoleMenuMapper.deletByMenuIds(ids);
	}

	@Override
	public List<SysMenu> getNotButtonList() {
	    return sysMenuMapper.getNotButtonList();
	}

	@Override
	public void save(SysMenu menu) {
		//当menu.getParentMenu().getMenuId()是空时
		//hibernate 会报告需要保存临时数据的错误，所以清空级联对象再保存
		if(menu.getParentMenu() != null && menu.getParentMenu().getMenuId() == null) {
			menu.setParentMenu(null);
		}
		sysMenuMapper.insert(menu);
	}

	@Override
	public SysMenu getById(Long menuId) {
	    return sysMenuMapper.selectByPrimaryKey(menuId);
	}

	@Override
	public void update(SysMenu menu) {
	    sysMenuMapper.updateByPrimaryKey(menu);
	}

	@Override
	public List<SysMenu> findAll() {
	    return sysMenuMapper.findAll();
	}

	@Override
	public List<String> getUserPermsList(Long userId) {
		List<String> userPermsList = sysMenuMapper.getUserPermsList(userId);
		List<String> finalPermsList = new ArrayList<String>();
		for(int i=0; i<userPermsList.size(); i++) {
			String perms = userPermsList.get(i);
			if(StringUtils.isBlank(perms)) {
				continue;
			}
			finalPermsList.addAll(Arrays.asList(perms.split(",")));
		}
		return finalPermsList;
	}

	@Override
	public List<SysMenu> getTopMenuList() {
		//用户id
		SysUser creator = (SysUser) SecurityUtils.getSubject().getPrincipal();
		Long id = creator.getUserId();
		List<Long> roleList = sysUserRoleMapper.findRoleList(id);
		if (roleList != null && roleList.size() != 0){
			Long roleId = roleList.get(0);
			return sysMenuMapper.getTopMenuList(roleId);
		}
		return null;
	}
}
